/*
 * Copyright (c) 2008-2009 Tomas Varaneckas
 * http://www.varaneckas.com
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.varaneckas.hawkscope.gui.settings;

import java.io.File;
import java.util.Arrays;
import java.util.Iterator;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;

import com.varaneckas.hawkscope.cfg.Configuration;
import com.varaneckas.hawkscope.gui.SharedStyle;

/**
 * Quick Access List Settings {@link TabItem}
 * 
 * @author Tomas Varaneckas
 * @version $Id: QuickAccessSettingsTabItem.java 420 2009-03-12 14:11:09Z tomas.varaneckas $
 */
public class QuickAccessSettingsTabItem extends AbstractSettingsTabItem {
    
    /**
     * Label "Quick Access Locations"
     */
    private Label labelQuickAccessLoc;
    
    /**
     * The Quick Access {@link List}
     */
    private List listQuickAccess;
    
    /**
     * Button that adds a Quick Access item
     */
    private Button buttonAddQa;
    
    /**
     * Button that deletes a Quick Access item
     */
    private Button buttonDelQa;
    
    /**
     * Button that moves a Quick Access item up
     */
    private Button buttonUpQa;
    
    /**
     * Button that moves a Quick Access item down
     */
    private Button buttonDnQa;
    
    /**
     * Creates the Quick Access settings {@link TabItem}
     * 
     * @param folder Settings {@link TabFolder}
     */
	public QuickAccessSettingsTabItem(final TabFolder folder) {
		super(folder, "&Quick Access");
		
		//Quick Access Locations
		labelQuickAccessLoc = addSectionLabel("Quick Access Locations");
		labelQuickAccessLoc.setLayoutData(SharedStyle.relativeTo(null, null));
		
		createButtonAddQa();
		createButtonDelQa();
		createListQuickAccess();
		createButtonDnQa();
		createButtonUpQa();
	}

	/**
	 * Creates {@link Button} that adds a Quick Access item
	 */
    private void createButtonAddQa() {
        buttonAddQa = addButton("&+");
        final FormData layout = SharedStyle.relativeTo(labelQuickAccessLoc, 
                null, null, null);
        layout.bottom = null;
        layout.left = null;
        layout.width = SharedStyle.BUTTON_MIN_WIDTH;
        buttonAddQa.setLayoutData(layout);
        buttonAddQa.setToolTipText("Add a Quick Access item");
        buttonAddQa.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(final SelectionEvent event) {
               final DirectoryDialog fd = new DirectoryDialog(folder.getShell(), 
                       SWT.OPEN);
               folder.getShell().setEnabled(false);
               fd.setMessage("Find a folder to add");
               fd.setText("Add to Quick Access List");
               final String item = fd.open();
               if (item != null && !Arrays.asList(listQuickAccess.getItems())
                       .contains(item)) {
                   listQuickAccess.add(item);
                   listQuickAccess.setToolTipText(item);
                   listQuickAccess.setSelection(
                           listQuickAccess.getItemCount() - 1);
               }
               folder.getShell().setEnabled(true);
            } 
        });
    }
    
    /**
     * Creates a {@link Button} that removes selected Quick Access item(s)
     */
    private void createButtonDelQa() {
        buttonDelQa = addButton("&-");
        final FormData layout = SharedStyle.relativeTo(buttonAddQa, 
                null, null, null);
        layout.bottom = null;
        layout.left = null;
        layout.width = SharedStyle.BUTTON_MIN_WIDTH;
        buttonDelQa.setLayoutData(layout);
        buttonDelQa.setToolTipText("Remove selected Quick Access item(s)");
        buttonDelQa.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(final SelectionEvent event) {
               for (final String s : listQuickAccess.getSelection()) {
                   listQuickAccess.remove(s);
               }
               listQuickAccess.setToolTipText("");
            } 
        });
    }
    
    /**
     * Creates a {@link Button} that moves a Quick Access item up
     */
    private void createButtonUpQa() {
        buttonUpQa = addButton("&Up");
        final FormData layout = SharedStyle.relativeTo(null, null, 
                buttonDnQa, null);
        layout.top = null;
        layout.left = null;
        layout.width = SharedStyle.BUTTON_MIN_WIDTH;
        buttonUpQa.setLayoutData(layout);
        buttonUpQa.setToolTipText("Move selected item up");
        buttonUpQa.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(final SelectionEvent event) {
               if (listQuickAccess.getSelectionCount() == 0) {
                   return;
               }
               if (listQuickAccess.getSelectionCount() > 1) {
                   showMoveWarnDialog();
                   return;
               }
               final int i = listQuickAccess.getSelectionIndex();
               //first item
               if (i == 0) {
                   return;
               }
               final String temp = listQuickAccess.getItem(i - 1);
               listQuickAccess.setItem(i - 1, listQuickAccess.getSelection()[0]);
               listQuickAccess.setItem(i, temp);
               listQuickAccess.setSelection(i - 1);
            }
        });
    }
    
    /**
     * Creates a {@link Button} that moves Quick Access item down
     */
    private void createButtonDnQa() {
        buttonDnQa = addButton("&Dn");
        final FormData layout = SharedStyle.relativeTo(null, null, null, null);
        layout.top = null;
        layout.left = null;
        layout.width = SharedStyle.BUTTON_MIN_WIDTH;
        buttonDnQa.setLayoutData(layout);
        buttonDnQa.setToolTipText("Move selected item down");
        buttonDnQa.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(final SelectionEvent event) {
               if (listQuickAccess.getSelectionCount() == 0) {
                   return;
               }
               if (listQuickAccess.getSelectionCount() > 1) {
                   showMoveWarnDialog();
                   return;
               }
               final int i = listQuickAccess.getSelectionIndex();
               //last item
               if (i == listQuickAccess.getItemCount() - 1) {
                   return;
               }
               final String temp = listQuickAccess.getItem(i + 1);
               listQuickAccess.setItem(i + 1, listQuickAccess.getSelection()[0]);
               listQuickAccess.setItem(i, temp);
               listQuickAccess.setSelection(i + 1);
            }
        });
    }
    
    /**
     * Shows warning when user is tring to move more than one selected item
     */
    private void showMoveWarnDialog() {
        final MessageBox mb = new MessageBox(folder.getShell(), SWT.ICON_WARNING);
        mb.setMessage("Please select only one item to move!");
        mb.setText("Hey!");
        folder.getShell().setEnabled(false);
        mb.open();
        folder.getShell().setEnabled(true);
    }     

    /**
     * Creates the Quick Access {@link List}
     */
    private void createListQuickAccess() {
        listQuickAccess = new List(container, 
                SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
        final FormData layout = ident(SharedStyle.relativeTo(
                labelQuickAccessLoc, buttonAddQa, null, null));
        layout.width = 250;
        layout.height = 120;
        listQuickAccess.setLayoutData(layout);
        listQuickAccess.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(final SelectionEvent event) {
               if (listQuickAccess.getSelectionCount() == 1) {
                   listQuickAccess
                       .setToolTipText(listQuickAccess.getSelection()[0]);
               }
            } 
        });
        final Iterator<File> qaFiles = cfg.getQuickAccessList().iterator();
        if (qaFiles.hasNext()) {
            for (final String qaItem : cfg.getRawQuickAccessList()) {
                try {
                    final String qaFile = qaFiles.next().getAbsolutePath()
                            .replaceAll("\\\\", "/");
                    if (!qaFile.equals(qaItem)) {
                        listQuickAccess.add(qaFile + " <" + qaItem + ">");
                    } else {
                        listQuickAccess.add(qaItem);
                    }
                } catch (final Exception e) {
                    log.warn("Processing invalid access entry: " + qaItem 
                            + ": " + e.getMessage(), e);
                }
            }
        }
    }

    @Override
    protected void saveConfiguration() {
        final StringBuilder quickAccess = new StringBuilder();
        for (final String item : listQuickAccess.getItems()) {
            quickAccess.append(item.replaceFirst(".+<", "")
                    .replaceFirst(">", "").replaceAll("\\\\", "/"));
            quickAccess.append(';');
        }
        cfg.getProperties().put(Configuration.QUICK_ACCESS_LIST, 
                quickAccess.toString());        
    }

}
